package com.learn.metrics.report.slf4j;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.logback.InstrumentedAppender;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author XuYang
 * @since 2025/2/19 11:01
 */
public class Slf4jReporterExample {
    static final Logger logger = ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger(Logger.ROOT_LOGGER_NAME);

    public static void start(Integer interval) {
        MetricRegistry registry = new MetricRegistry();

        // 打印统计信息
        Slf4jReporter.forRegistry(registry).withLoggingLevel(Slf4jReporter.LoggingLevel.INFO).build().start(interval, TimeUnit.SECONDS);

        final InstrumentedAppender metrics = new InstrumentedAppender(registry);
        metrics.setContext(logger.getLoggerContext());
        metrics.start();
        logger.addAppender(metrics);
        int count = 0;
        while (count++ < 10) {
            logger.warn("################## 分隔 ##################");
            ThreadUtil.sleep(RandomUtil.randomInt(500, 1000));
        }
    }
}
